#!/usr/bin/env python3
"""
Simple test script for the weather prediction AI system.
Tests basic functionality without requiring PyTorch installation.
"""

import pandas as pd
import numpy as np
import os
from datetime import datetime, timedelta
import tempfile

def test_data_structure():
    """Test basic data structure and CSV handling"""
    print("Testing data structure and CSV handling...")
    
    # Test CSV file creation and reading
    test_data = []
    base_time = datetime(2024, 1, 1, 0, 0, 0)
    
    for i in range(24):  # 24 hours of data
        timestamp = base_time + timedelta(hours=i)
        test_data.append({
            'timestamp': timestamp.strftime("%Y-%m-%d %H:%M:%S"),
            'station_id': 'TEST001',
            'DNI': 800 + 50 * np.sin(i/24 * 2*np.pi),
            'DHI': 200 + 50 * np.cos(i/24 * 2*np.pi),
            'temperature': 15 + 10 * np.sin(i/24 * 2*np.pi),
            'wind_speed': 5 + 3 * np.sin(i/12 * 2*np.pi),
            'wind_direction': 180 + 90 * np.sin(i/8 * 2*np.pi)
        })
    
    # Create DataFrame
    df = pd.DataFrame(test_data)
    print(f"✓ Created test DataFrame with {len(df)} rows")
    print(f"✓ Columns: {list(df.columns)}")
    
    # Test CSV save/load
    with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as f:
        df.to_csv(f.name, index=False)
        temp_csv_path = f.name
    
    try:
        # Load back from CSV
        loaded_df = pd.read_csv(temp_csv_path)
        print(f"✓ CSV loaded successfully: {len(loaded_df)} rows")
        print(f"✓ Data types: {loaded_df.dtypes}")
        
        # Test timestamp conversion
        loaded_df['timestamp'] = pd.to_datetime(loaded_df['timestamp'])
        print("✓ Timestamp conversion successful")
        
    finally:
        os.unlink(temp_csv_path)
    
    print("✓ Data structure test passed!\n")

def test_config_loading():
    """Test configuration file loading"""
    print("Testing configuration file loading...")
    
    try:
        import yaml
        
        # Test if config file exists and is valid YAML
        if os.path.exists('config.yaml'):
            with open('config.yaml', 'r') as f:
                config = yaml.safe_load(f)
            print("✓ Config file loaded successfully")
            print(f"✓ Historical days: {config['data']['historical_days']}")
            print(f"✓ Future days: {config['data']['future_days']}")
        else:
            print("⚠ Config file not found, but that's okay for this test")
            
    except ImportError:
        print("⚠ yaml module not available, skipping config test")
    except Exception as e:
        print(f"⚠ Config test failed: {e}")
    
    print("✓ Config loading test completed\n")

def test_directory_structure():
    """Test project directory structure"""
    print("Testing project directory structure...")
    
    required_files = [
        'requirements.txt',
        'config.yaml',
        'data_utils.py',
        'models.py',
        'train.py',
        'predict.py',
        'test_system.py',
        'README.md'
    ]
    
    for file in required_files:
        if os.path.exists(file):
            print(f"✓ {file} exists")
        else:
            print(f"⚠ {file} missing")
    
    # Check if data directories exist or can be created
    data_dirs = ['./data/himawari/', './checkpoints/', './logs/', './predictions/']
    for dir_path in data_dirs:
        try:
            os.makedirs(dir_path, exist_ok=True)
            print(f"✓ Directory {dir_path} ready")
        except Exception as e:
            print(f"⚠ Could not create directory {dir_path}: {e}")
    
    print("✓ Directory structure test completed\n")

def main():
    """Run all simple tests"""
    print("=" * 60)
    print("WEATHER PREDICTION AI SYSTEM - BASIC FUNCTIONALITY TEST")
    print("=" * 60)
    
    try:
        test_data_structure()
        test_config_loading()
        test_directory_structure()
        
        print("=" * 60)
        print("✅ BASIC TESTS COMPLETED!")
        print("=" * 60)
        print("\nSystem structure is ready. Next steps:")
        print("1. Install dependencies: pip install -r requirements.txt")
        print("2. Add real station data to station_data.csv")
        print("3. Add satellite data to ./data/himawari/ directory")
        print("4. Train the model: python train.py")
        print("5. Make predictions: python predict.py")
        
    except Exception as e:
        print(f"❌ Test failed with error: {e}")
        import traceback
        traceback.print_exc()
        return 1
    
    return 0

if __name__ == "__main__":
    exit(main())
